package org.robot.scm.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

@Slf4j
public class AuthDecryptUtil {

    public static String baseUrl;

    private static final Map<String, String> headers = new HashMap<String, String>() {{
        put("clienttoken", "8e0c7a939587c3b5c91d04b756dc6be7");
    }};

    /**
     * 获取设备信息
     */
    public static JSONObject getDeviceInfo() {
        String iResult = RequestHelper.post(baseUrl, "method=list");
        JSONObject ires = JsonHelper.toObject(iResult, JSONObject.class);
        JSONArray iArray = ires.getJSONArray("data");
        if (iArray.isEmpty() || iArray.getJSONObject(0).getInteger("isLogin") != 1) {
            throw new RuntimeException("请先启动并且登录一个微信");
        }
        return iArray.getJSONObject(0);
    }

    /**
     * 触发验证码
     */
    public static JSONObject touchCapture() {
        String getCaptureUrl = "https://api.adfortest.com/v1/07ff0f03d3e44fb82186197c1460056b?type=check&clientToken=8e0c7a939587c3b5c91d04b756dc6be7&_=" + new Date().getTime();
        String gResult = RequestHelper.get(getCaptureUrl, headers);
        JSONObject gres = JsonHelper.toObject(gResult, JSONObject.class);
        Integer resgCode = gres.getInteger("code");
        if (resgCode != 200) {
            throw new RuntimeException("获取验证码失败");
        }
        return gres.getJSONObject("data");
    }

    /**
     * 点击验证码
     */
    @SneakyThrows
    public static String clickCapture(JSONArray jsonArray) {
        String checkToken = "";
        // 固定刷第一个验证按钮，碰运气
        String verifyUrl = "https://api.adfortest.com/v1/07ff0f03d3e44fb82186197c1460056b/1?clientToken=8e0c7a939587c3b5c91d04b756dc6be7&_=" + new Date().getTime();
        String vResult = RequestHelper.post(verifyUrl, headers, null);
        JSONObject vres = JsonHelper.toObject(vResult, JSONObject.class);
        Integer resvCode = vres.getInteger("code");
        if (resvCode == 200) {
            checkToken = URLEncoder.encode(vres.getJSONObject("data").getString("checkToken"), StandardCharsets.UTF_8.name());
        }
        if (StringUtils.isEmpty(checkToken)) {
            throw new RuntimeException("验证失败, 请重试");
        }
        return checkToken;
    }

    /**
     * 获取进程信息
     */
    public static JSONObject queryProcess(Integer pid) {
        String mResult = RequestHelper.post(baseUrl, "pid=" + pid + "&method=mac");
        return JsonHelper.toObject(mResult, JSONObject.class);
    }

    /**
     * 确认授权
     */
    @SneakyThrows
    public static void confirmAuth(Integer pid, String token, String auth) {
        String cData = "pid=" + pid + "&method=auth&token=%s";
        String cResult = RequestHelper.post(baseUrl, String.format(cData, URLEncoder.encode(token, StandardCharsets.UTF_8.name())));
        JSONObject cres = JsonHelper.toObject(cResult, JSONObject.class);
        Integer cStatus = cres.getInteger("status");
        if (cStatus == 1) {
            log.info("auth expire: {}", auth);
            return;
        }
        log.error("authed fail, error: {}", cResult);
    }

    /**
     * 执行授权
     */
    public static JSONObject executeAuth(String wxid, String pcid, String data, String checkToken) {
        String baseAuthUrl = baseUrl.split("/api")[0];
        String sid = "72C8D320846101224B5BFDEEA2DFF79A1E62CF7166A8A1E719B80EDD6A5487EE1C2596B00CEA259F89C8221F5295D743088E1B0453BC127D09CA90C94F02077CCF3EDA8CDBA51183EC0784DB80BF826A1898C329CEBCED0E6E456680770C6E53125BFA6DF34F7AA682665D650B4C56F4802D80520BAC170DDC903A2AA27342DA";
        String authUrl = baseAuthUrl + "/proxy/api/auth?app=1&auth=ls&sid=%s&wxid=" + wxid + "&pcid=%s&data=%s&checkToken=%s";
        String aResult = RequestHelper.post(String.format(authUrl, sid, pcid, data, checkToken), Maps.newHashMap(), null);
        JSONObject ares = JsonHelper.toObject(aResult, JSONObject.class);
        Boolean status = ares.getBoolean("status");
        if (Objects.isNull(status) || !status) {
            throw new RuntimeException("授权请求失败, 请重试");
        }
        return ares.getJSONObject("data");
    }

}
